const xlsx = require("xlsx-js-style");

function getSheet1(
  data,
  merges = [],
  cols = [
    { wch: 30 },
    { wch: 30 },
    { wch: 30 },
    { wch: 30 },
    { wch: 30 },
    { wch: 30 },
    { wch: 30 },
  ],
  rows = [],
  freezepane = {}
) {
  const sheet = xlsx.utils.aoa_to_sheet(data); // aoa_to_sheet 将二维数组转成 sheet
  //合并规则
  // const merges = [
  //   { s: { r: 1, c: 0 }, e: { r: 4, c: 0 } },
  //   { s: { r: 5, c: 0 }, e: { r: 8, c: 0 } },
  // ];
  sheet["!merges"] = merges; // 将merges添加到sheet中，设置合并单元格
  // const cols = [
  //   { wch: 30 },
  //   { wch: 30 },
  //   { wch: 30 },
  //   { wch: 30 },
  //   { wch: 30 },
  //   { wch: 30 },
  //   { wch: 30 },
  // ];
  sheet["!cols"] = cols; // 将cols添加到sheet中，设置列宽
  // const rows = [{ hpx: 30 }, { hpx: 26 }, { hpx: 28 }];
  sheet["!rows"] = rows; // 将rows添加到sheet中，设置行高

  return sheet;
}
/*
      util.default.exportExcel(
            [
              {
                name: "sheet_cy",
                data: [
                  ["姓名", "年龄"],
                  ["cy", "18"],
                  ["zq", "16"],
                ],
              },
              {
                name: "sheet_za",
                data: [
                  ["name", "age"],
                  ["cy", "18"],
                  ["zq", "16"],
                ],
              },
            ],
            "cytest.xlsx"
          );
   * */
function exportExcel(list, fileName = "excel名称.xlsx") {
  const workbook = xlsx.utils.book_new(); // 创建虚拟的 workbook
  list?.map((item) => {
    const sheet = getSheet1(
      item?.data,
      item?.merges || [],
      item?.cols || [],
      item?.rows || [],
      item?.freezepane || {}
    ); // 向 workbook 中添加 sheet
    xlsx.utils.book_append_sheet(workbook, sheet, item?.name);
  });
  xlsx.writeFile(workbook, fileName); // 导出 workbook
}

module.exports = {
  exportExcel,
};
